\chapter{Data}

\section{Server Data Model}

\subsection{Overview}
The odel implementation exploit the App Engine Dadastore which is a schema-less object-oriented datastore.

We decided to build our service on this envirorment because it offers the possibility of automatic caching and scaling of the datastore and performance improvements follow a common PaaS bussiness model. Moreover the service is free under certain dayly limitations.

Google offers a Java SKD which includes both JDO and JPA interfaces and implementations.
Objectify, is an additional framework that we decide to use to simplify the complexity presented by JDO/JPA and the low-level Datastore API.


\subsection{ER Diagram}

\subsection{Logic Diagram}

The model behind our system is developped in order to be very scalable from the content point of view. Since our application behavihour can change according to the evaluation task in italian universities we needed to build a service that was both enough simple and reactive to big change in content organization. 
For this reason we minimized the singe entity dimension splitting single functionality in smaller subentities which can be easily managed.

\begin{lstlisting}

ACHIEVEMENT(Id, test, image)
NOTIFICATION(Id, target, timestamps, content, type)
SYSTEM UPDATE(Id, target, ts, content)
MESSAGE(Id, Sender, Receiver, content)

USER(Id, Name, Surname, Sex, email, password, birth date, location, minibio, premium, role)
FRIENDSHIP(User1, User2)

USER ACHIEVEMENT(User, Achievement, Timestamps)
USER STATISTICS(User, Subject, Wrong, Right)
BOOKMARK QUESTION(User, Question, ts)

TEST(Id, User-Id, Question, mode)
TEST SHADOW(Id, User-Id, Subject, duration, difficulty)
TEST STATISTICS(Id, User, Subject, wrong, right, duration, difficuly)

ANSWER(Id, Question, Text, value)
QUESTION(Id, Subject, difficulty, card, subject, Image)

SUBJECT(Id,name, code, time, coefficient, topic_link)    
TEST LAYOUT(Id, name, time, difficulty)
TEST COMPOSITION(Layout-Id, Subject-Id, Quantity)



\end{lstlisting}



\section{SQLite Database}

Thinking our mobile application as a client for the web service we consider to reduce the model we need on the go. 
First of all we don't consider the presence of a user entity because it is presented by the client itself, we only need some informations from the user actor to identify and authenticate him. This information can be stored to reduce the request by the application to the user; we do this by using the SharedPreferences utility offered by Android, a detailed description is in the section: 4.1.

The other information that we need to store inside our Mobile Client are question Question and Answers. We also report the Test as an entity to perform some local elaboration about it waiting for the online test corruption which depends on the internet connection.

We exploit  a SQLite database to store all of these information on user's device. The most relevant operation which involve the database is the test performing task, that envelop in this way:

When a user start a new test, we request a test with the TestAPI and we save it in the local database. We made this choice to provide users the possibility to make test even if network connection is disabled or not reliable. The correction Service, which request internet connection to correct and save the stats online, start only when the user decide to complete the test, and it is complete independent from the test correction which can be immediately looked inside the application. More on the Correct Service in the section: 4.2.2.

\subsection{SQLite ER Diagram}

\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{images/sqlite-db}
\caption{ER Diagram of the SQLite Database.}
\end{figure}

\subsection{SQLite Logic Diagram}

We created three entities: \textsf{Test}, \textsf{Question} and \textsf{Answer}.
\begin{itemize}
\item \textsc{Test}(\underline{test\_id}, user\_id, appengine\_id)
\item \textsc{Question}(\underline{question\_id}, test\_id, question\_text, subject, appengine\_id, image)
\item \textsc{Answer}(\underline{answer\_id}, question\_id, answer\_text, value, appengine\_id)
\end{itemize}


\subsection{Database creation}


\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{images/sql-cd}
\caption{SQL Utils Class Diagram.}
\end{figure}



Android provides full support for SQLite databases. The database we created is accessible by name to any class in our application, but not outside it.
We created a subclass of \textsf{SQLiteOpenHelper} and override the \textsf{onCreate()} method, in which we execute a SQLite command to create tables in the database. 

\begin{lstlisting}
public class TBDatabaseHelper extends SQLiteOpenHelper {

	// Database Version
	private static final int DATABASE_VERSION = 42;
	
	// Database Name
	private static final String DATABASE_NAME = "TBDatabase";
	
	/* ... */
	
		// Constructor
	public TBDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// creating required tables
		db.execSQL(CREATE_TABLE_TEST);
		db.execSQL(CREATE_TABLE_QUESTION);
		db.execSQL(CREATE_TABLE_ANSWER);
	}
	
	/* ... */
}
\end{lstlisting}

We can then get an instance of our \textsf{TBDatabaseHelper} implementation using the constructor we've defined. To write to and read from the database, we call \textsf{getWritableDatabase()} and \textsf{getReadableDatabase()}, respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.

\subsection{Table Test example}

We can execute SQLite queries using the SQLiteDatabase \textsf{query()} methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others. Every SQLite query return a \textsf{Cursor} that points to all the rows found by the query. We used this mechanism to navigate results from a query and read rows and columns.
Here we present an example of a query method inside our \textsf{TBDatabaseHelper} to collect every test correlated to a given user.

\begin{lstlisting}
public List<TestSQLite> getAllTestByUser(String user_id) {
	SQLiteDatabase db = this.getReadableDatabase();
	List<TestSQLite> tests = new ArrayList<TestSQLite>();

	String selectQuery = "SELECT  * FROM " + TABLE_TEST + " WHERE "
			+ COLUMN_TEST_USER_ID + " = " + user_id;

	Cursor c = db.rawQuery(selectQuery, null);

	if (c.moveToFirst()) {
		do {
			TestSQLite t = new TestSQLite();
			t.setTestId(c.getInt((c.getColumnIndex(COLUMN_TEST_ID))));
			t.setUserId(c.getString(c.getColumnIndex(COLUMN_TEST_USER_ID)));
			t.setAppengineId(c.getString(c
					.getColumnIndex(COLUMN_TEST_GAE_ID)));

			tests.add(t);
		} while (c.moveToNext());
	}

	return tests;
}
\end{lstlisting}
We wrote the SQL query and used the \textsf{Cursor} returned to collect in a list all the tests found. We created a  \textsf{TestSQLite} Java class as an adapter between the SQLiteDatabase and our application. The attribute \textsf{appengineId} allow us to retrive the test from the server through the TestEndpoint and to save the statistics also online.